//
//  DataViewController.m
//  LiveSoftware
//
//  Created by lanou3g on 15/7/10.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "DataViewController.h"

@interface DataViewController () <UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@property(nonatomic,strong) NSMutableArray *teamOrderArray;
@property(nonatomic,strong) NSMutableArray *scoreOrderArray;
@property(nonatomic,strong) NSMutableArray *assistOrderArray;

@end

static DataViewController *dataVC;

@implementation DataViewController

+ (DataViewController *)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataVC = [[DataViewController alloc] init];
    });
    return dataVC;
}

- (void)requestData
{
    // 解析积分榜
    [LORequestManger GET:self.teamOrderUrl success:^(id response) {
        NSDictionary *superDict = (NSDictionary *)response;
        NSDictionary *resultDict = [superDict valueForKey:@"result"];
        NSDictionary *dataDict = resultDict[@"data"];
        NSArray *array = dataDict[@""];
//        NSArray *groups = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H"];
//        for (int i = 0; i < 8; i++) {
//            NSArray *ouguanTeam = dataDict[groups[i]];
//            for (NSDictionary *ouguanModel in ouguanTeam) {
//                FootballTeamOrderModel *teamOrderModel = [FootballTeamOrderModel footballTeamOrderModelWithDict:ouguanModel];
//                [self.teamOrderArray addObject:teamOrderModel];
//            }
//        }
        self.teamOrderArray = [NSMutableArray array];
        for (NSDictionary *smallDict in array) {
            FootballTeamOrderModel *teamOrderModel = [FootballTeamOrderModel footballTeamOrderModelWithDict:smallDict];
            [self.teamOrderArray addObject:teamOrderModel];
        }
        [self.dataView.leftTableView reloadData];
        self.dataView.titleLabel.text = self.leagueName;
        

            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"网络错误");
    }];
    // 解析射手榜
    [LORequestManger GET:self.scoreOrderUrl success:^(id response) {
        NSDictionary *superDict = (NSDictionary *)response;
        NSDictionary *resultDict = [superDict valueForKey:@"result"];
        NSArray *dataArray = resultDict[@"data"];
        self.scoreOrderArray = [NSMutableArray array];
        for (NSDictionary *smallDict in dataArray) {
            FootballScoreOrderModel *scoreOrderModel = [FootballScoreOrderModel footballScoreOrderModelWithDict:smallDict];
            [self.scoreOrderArray addObject:scoreOrderModel];
        }
        NSLog(@"射手榜数组%lu",(unsigned long)self.scoreOrderArray.count);
        [self.dataView.centerTableView reloadData];
        [self setBackImageWhenNoData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"解析出错");
    }];
    // 解析助攻榜
    [LORequestManger GET:self.assistOrderUrl success:^(id response) {
        NSDictionary *superDict = (NSDictionary *)response;
        NSDictionary *resultDict = [superDict valueForKey:@"result"];
        NSArray *dataArray = resultDict[@"data"];
        self.assistOrderArray = [NSMutableArray array];
        for (NSDictionary *smallDict in dataArray) {
            FootballAssistOrderModel *assistOrderModel = [FootballAssistOrderModel footballAssistOrderModelWithDict:smallDict];
            [self.assistOrderArray addObject:assistOrderModel];
        }
        [self.dataView.rightTableView reloadData];
        [self setBackImageWhenNoData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"解析出错");
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.dataTableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
//    self.dataTableView.backgroundView = self.dataView;
//    self.view = self.dataTableView;
    
    self.teamOrderUrl = kChineseSuperLeagueTeamOrderUrl;
    self.scoreOrderUrl = kChineseSuperLeagueScoreOrderUrl;
    self.assistOrderUrl = kChineseSuperLeagueAssistOrderUrl;
    self.leagueName = @"中超";
    [self requestData];

    self.dataView = [[DataView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = _dataView;

    self.dataView.baseScrollView.delegate = self;
    self.dataView.leftTableView.delegate = self;
    self.dataView.leftTableView.dataSource = self;
    self.dataView.centerTableView.delegate = self;
    self.dataView.centerTableView.dataSource = self;
    self.dataView.rightTableView.delegate = self;
    self.dataView.rightTableView.dataSource = self;
    
    self.dataView.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.dataView.centerTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.dataView.rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.dataView.teamOrderBtn addTarget:self action:@selector(teamOrderBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.dataView.scoreOrderBtn addTarget:self action:@selector(scoreOrderBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.dataView.assistOrderBtn addTarget:self action:@selector(assistOrderBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self pullDownToRefresh];
    
    [self setupLeftMenuButton];
    
}



-(void)setupLeftMenuButton{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    
    leftButton.frame = CGRectMake(kScreenIp6(10), kScreenIp6(30), kScreenIp6(20), kScreenIp6(25));
//    leftButton.backgroundColor = [UIColor redColor];
    leftButton.center = CGPointMake(kScreenIp6(20), self.dataView.titleLabel.center.y + kScreenIp6(1));
    
    [leftButton setBackgroundImage:[UIImage imageNamed:@"set_arrow_back_white"] forState:UIControlStateNormal];
    [leftButton setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
    [leftButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.dataView addSubview:leftButton];
    
    UIButton *centerButton = [UIButton buttonWithType:UIButtonTypeSystem];
    CGFloat centerButtonX = kScreenIp6(45);
//    centerButton.backgroundColor = [UIColor orangeColor];

    centerButton.frame = CGRectMake(centerButtonX, kScreenIp6(25), kScreenIp6(50), kScreenIp6(30));
//    self.dataView.titleLabel.backgroundColor = [UIColor grayColor];
    centerButton.center = CGPointMake(centerButtonX, self.dataView.titleLabel.center.y) ;
    [centerButton addTarget:self action:@selector(jumpBtn:) forControlEvents:UIControlEventTouchUpInside];
    [centerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [centerButton setTitle:@"联赛" forState:UIControlStateNormal];
    [self.dataView addSubview:centerButton];
    
}

// 点击button的事件
- (void)buttonAction:(UIButton *)button
{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    NSLog(@"点击了按钮");
    [self.mm_drawerController openSide];
}

- (void)jumpBtn:(UIButton *)button
{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    NSLog(@"点击了按钮");
    [self.mm_drawerController openDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    
    
    
    

}

#pragma mark - 下拉刷新
- (void)pullDownToRefresh
{
    __unsafe_unretained typeof(self) vc = self;
    [self.dataView.leftTableView addLegendHeaderWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
           [vc requestData];
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [vc.dataView.leftTableView.header endRefreshing];
        });
    }];
    
    [self.dataView.centerTableView addLegendHeaderWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [vc requestData];
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [vc.dataView.centerTableView.header endRefreshing];
        });
    }];
    
    [self.dataView.rightTableView addLegendHeaderWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [vc requestData];
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [vc.dataView.rightTableView.header endRefreshing];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.dataView.leftTableView) {
        
        return self.teamOrderArray.count;
    }
    else if (tableView == self.dataView.centerTableView)
    {
        return self.scoreOrderArray.count;
    }
    else
    {
        return self.assistOrderArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *cellID = @"cell";
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    if (tableView == self.dataView.leftTableView) {
        [tableView registerClass:[FootballTeamOrderTableViewCell class] forCellReuseIdentifier:cellID];
        FootballTeamOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        // 设置 cell 点击没有变化
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        FootballTeamOrderModel *model = self.teamOrderArray[indexPath.row];
            [cell setDataWithModel:model];
//        NSLog(@"cell====================%@",model.team_cn);
        if ([model.champions_league isEqualToString:@"1"] ) {
            cell.cellBackImageView.image = [UIImage imageNamed:@"header_bg_green_2"];
        }
        else if ([model.champions_league isEqualToString:@"-1"])
        {
            cell.cellBackImageView.image = [UIImage imageNamed:@"header_bg_lightgray@2x"];
        }
        else
        {
            cell.cellBackImageView.image = [UIImage imageNamed:@"header_bg_white@2x"];
        }
        return cell;

    }
    else if (tableView == self.dataView.centerTableView)
    {
        [tableView registerClass:[FootballScoreOrderTableViewCell class] forCellReuseIdentifier:cellID];
        FootballScoreOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        // 设置 cell 点击没有变化
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        

            FootballScoreOrderModel *model = self.scoreOrderArray[indexPath.row];
            for (FootballTeamOrderModel *teamModel in self.teamOrderArray) {
                if ([model.team_name isEqualToString:teamModel.team_cn]) {
                    [cell.logo setImageWithURL:[NSURL URLWithString:teamModel.logo] placeholderImage:[UIImage imageNamed:@"placeholder_pic_1"]];
                }
            [cell setDataWithScoreOrderModel:model];
                [self setBackImageWhenNoData];

        }
        return cell;
    }
        else
        {
            [tableView registerClass:[FootballAssistOrderTableViewCell class] forCellReuseIdentifier:cellID];
            FootballAssistOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            // 设置 cell 点击没有变化
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            FootballAssistOrderModel *model = self.assistOrderArray[indexPath.row];
            for (FootballTeamOrderModel *teamModel in self.teamOrderArray) {
                if ([model.team_name isEqualToString:teamModel.team_cn]) {
                    [cell.logo setImageWithURL:[NSURL URLWithString:teamModel.logo] placeholderImage:[UIImage imageNamed:@"placeholder_pic_1"]];
                }
            }
            [cell setDataWithAssistOrderModel:model];
            [self setBackImageWhenNoData];

        return cell;
    }
}


- (void)setBackImageWhenNoData
{
    //没有关注的时候
    UIView *noDataView = [[UIView alloc]initWithFrame:CGRectMake(kScreenWidth*2, 0, kScreenWidth, kScreenHeight)];
    noDataView.backgroundColor = [UIColor whiteColor];
    
    UIView *scoreNoDataView = [[UIView alloc]initWithFrame:CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight)];
    scoreNoDataView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *pointPicture = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth/2 - kScreenIp6(100), kScreenIp6(100), kScreenIp6(200), kScreenIp6(200))];
    pointPicture.image = [UIImage imageNamed:@"Empty_Hint_ZZZ@2x"];
    
    UIImageView *scorePic = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth/2 - kScreenIp6(100), kScreenIp6(100), kScreenIp6(200), kScreenIp6(200))];
    scorePic.image = [UIImage imageNamed:@"Empty_Hint_ZZZ@2x"];
    UILabel *attention = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth/2 - kScreenIp6(200), kScreenIp6(100), kScreenIp6(200), kScreenIp6(200))];
    attention.backgroundColor = [UIColor redColor];
    attention.text = @"共同期待新赛季的到来";
    attention.textAlignment = NSTextAlignmentCenter;
    attention.font = [UIFont systemFontOfSize:15];
    
    [noDataView addSubview:pointPicture];
    [scoreNoDataView addSubview:scorePic];
    if (self.scoreOrderArray.count == 0) {
        [self.dataView.baseScrollView addSubview:scoreNoDataView];
    }
    
    else
    {
        [scoreNoDataView removeFromSuperview];
        [self.dataView.baseScrollView addSubview:self.dataView.centerTableView];

    }
    
    if (self.assistOrderArray.count == 0) {

        [self.dataView.baseScrollView addSubview:noDataView];
    }
    else
    {
        [noDataView removeFromSuperview];
        [self.dataView.baseScrollView addSubview:self.dataView.rightTableView];

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kScreenIp6(50);
}

#pragma mark - 自定义分区表头
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kScreenIp6(30);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == self.dataView.leftTableView) {
        FootballTeamOrderHeaderView *header = [[FootballTeamOrderHeaderView alloc] init];
        return header;
    }
    else if (tableView == self.dataView.centerTableView)
    {
        FootballScoreOrderHeaderView *header = [[FootballScoreOrderHeaderView alloc] init];
        return header;
    }
    else
    {
        FootballAssistOrderHeaderView *header = [[FootballAssistOrderHeaderView alloc] init];
        return header;
    }
}



#pragma mark - Button点击方法
- (void)teamOrderBtnAction
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    
    
    self.dataView.baseScrollView.contentOffset = CGPointMake(0, 0);
    [self switchButtonPoint];
    
    
    [UIView commitAnimations];
    [self.dataView.leftTableView reloadData];
    
}
- (void)scoreOrderBtnAction
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    
    
    self.dataView.baseScrollView.contentOffset = CGPointMake(kScreenWidth, 0);
    [self switchButtonPoint];
    
    
    [UIView commitAnimations];
    [self.dataView.centerTableView reloadData];
    [self setBackImageWhenNoData];
}

- (void)assistOrderBtnAction
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    
    self.dataView.baseScrollView.contentOffset = CGPointMake(kScreenWidth * 2, 0);
    [self switchButtonPoint];
    
    [UIView commitAnimations];
    [self.dataView.rightTableView reloadData];
    [self setBackImageWhenNoData];
}


#pragma mark - 拖动中执行
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    
    int i = (self.dataView.baseScrollView.contentOffset.x + kScreenWidth/2) / kScreenWidth;
    self.dataView.pointImage.center = CGPointMake((i * kScreenWidth/3 + kScreenWidth/6), kScreenIp6(106));    
    [UIView commitAnimations];
}

#pragma mark 拖拽后减速停止触发
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDelegate:self];
    
    [self switchButtonPoint];
    
    [UIView commitAnimations];
    
    if (scrollView.contentOffset.x == kScreenWidth || scrollView.contentOffset.x == kScreenWidth * 2)
    {
        
        [self setBackImageWhenNoData];
        
    }
}

// 切换 Button 指向
- (void)switchButtonPoint
{
    if (self.dataView.baseScrollView.contentOffset.x == 0)
    {
        self.dataView.pointImage.center = CGPointMake(kScreenWidth/6, kScreenIp6(106));
        [self.dataView.teamOrderBtn setTintColor:[UIColor whiteColor]];
        [self.dataView.scoreOrderBtn setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
        [self.dataView.assistOrderBtn setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
    }
    else if (self.dataView.baseScrollView.contentOffset.x == kScreenWidth)
    {
        self.dataView.pointImage.center = CGPointMake(kScreenWidth/2, kScreenIp6(106));
        [self.dataView.scoreOrderBtn setTintColor:[UIColor whiteColor]];
        [self.dataView.teamOrderBtn setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
        [self.dataView.assistOrderBtn setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
    }
    else
    {
        self.dataView.pointImage.center = CGPointMake(kScreenWidth*5/6, kScreenIp6(106));
        [self.dataView.assistOrderBtn setTintColor:[UIColor whiteColor]];
        [self.dataView.scoreOrderBtn setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
        [self.dataView.teamOrderBtn setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
    }
}



#pragma mark - 视图消失和出现
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
}
@end
